#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_player = new QMediaPlayer;
    m_audioOutput = new QAudioOutput;
    m_widget = new QVideoWidget(ui->videoLabel);//播放标签作为父控件
    m_player->setAudioOutput(m_audioOutput);
    m_player->setVideoOutput(m_widget);
    m_widget->resize(ui->videoLabel->size());
    ui->voiceSlider->setRange(0,100);
    ui->voiceSlider->setValue(20);
    ui->videoSlider->setValue(0);
    m_audioOutput->setVolume(20);
    ui->comboBox->setCurrentText("1.0");
    ui->beginBtn->setEnabled(false);
    connect(m_player,&QMediaPlayer::durationChanged,this,[=](qint64 dur){
        ui->videoSlider->setRange(0,(int)dur);
        ui->totalTimeLabel->setText(QString("%1:%2").arg(dur/60000,2,10,QChar('0')).arg(dur/1000%60,2,10,QChar('0')));
    });
    connect(m_player,&QMediaPlayer::positionChanged,this,[=](qint64 pos){
        ui->videoSlider->setValue(pos);
    });

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_openBtn_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this,tr("选择视频或音频"),"D:\\",tr("视频文件 (*.mp4);;音频文件 (*.mp3)"));
    m_player->setSource(QUrl::fromLocalFile(filePath));
    ui->beginBtn->setEnabled(true);
}


void Widget::on_backwardBtn_clicked()
{
    qint64 currentpos = m_player->position();
    m_player->setPosition(currentpos-5000);//后退5秒
}


void Widget::on_beginBtn_clicked()
{
    if(!isPlaying){
        m_player->play();
        ui->beginBtn->setIcon(QIcon(":/images/begin.png"));
        isPlaying = true;
    }else{
        m_player->pause();
        ui->beginBtn->setIcon(QIcon(":/images/pause.png"));
        isPlaying = false;
    }
}


void Widget::on_forwardBtn_clicked()
{
    qint64 currentPos = m_player->position();
    m_player->setPosition(currentPos+5000);
}


void Widget::on_voiceSlider_valueChanged(int value)
{
    m_audioOutput->setVolume(value);
}


void Widget::on_videoSlider_valueChanged(int value)
{
    ui->currentTimeLabel->setText(QString("%1:%2")
                                      .arg(value / 60000, 2, 10, QChar('0'))
                                      .arg((value / 1000) % 60, 2, 10, QChar('0')));
}


void Widget::on_comboBox_currentTextChanged(const QString &arg1)
{
    if(arg1 == "1.0"){
        m_player->setPlaybackRate(1);
    }else if(arg1 == "0.75"){
        m_player->setPlaybackRate(0.75);
    }else if(arg1 == "1.25"){
        m_player->setPlaybackRate(1.25);
    }else if(arg1 == "1.5"){
        m_player->setPlaybackRate(1.5);
    }
}



void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    m_widget->resize(ui->videoLabel->size());
}


void Widget::on_videoSlider_sliderPressed()
{
    m_player->pause();  // 滑块按下时暂停播放
}


void Widget::on_videoSlider_sliderReleased()
{
    m_player->setPosition(ui->videoSlider->value()); // 设置新的播放位置
    m_player->play();   // 恢复播放
}

